<template>
  <div>
    <Header :left="true" leftText="返回" title="并修时长查询" />
    <div>
      <DropdownMenu style="margin-top: 10px; background-color: #d3d3d3">
        <DropdownItem
          v-model="siteIndex"
          :options="sites"
          @change="siteChange"
        />
        <!-- <DropdownItem
          v-model="departIndex"
          :options="departments"
          @change="departChange"
        /> -->
        <DropdownItem ref="time" title="时间" @open="showDialog = true" />
      </DropdownMenu>
    </div>
    <van-dialog
      v-model="showDialog"
      title="查询条件选择"
      show-cancel-button
      confirm-button-text="确认"
      cancel-button-text="取消"
      @confirm="timeConfirm"
      @cancel="clearTime"
    >
      <Form :style="autoHeight">
        <van-field
          readonly
          clickable
          name="timeStr"
          :value="valueStr"
          label="开始时间"
          placeholder="点击选择日期"
          @click="openStartTime"
        />
        <van-calendar
          v-model="showCalendarStr"
          @confirm="onConfirmStr"
          @closed="startConcel"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-field
          readonly
          clickable
          name="timeEnd"
          :value="valueEnd"
          label="结束时间"
          placeholder="点击选择日期"
          @click="openEndTime"
        />
        <van-calendar
          v-model="showCalendarEnd"
          @confirm="onConfirmEnd"
          @closed="endConcel"
          :min-date="minDate"
          :max-date="maxDate"
        />
      </Form>
    </van-dialog>
    <!-- 统计图 -->
    <!-- 条形图 -->
    <!-- <div>
        <canvas id="mountNode" style="width:100%;height:250px;"></canvas>
      </div> -->
    <!-- <van-divider>表格统计</van-divider> -->
    <div>
      <v-table
        is-horizontal-resize
        style="width: 100%"
        :show-vertical-border="true"
        :columns="columns"
        :table-data="tableData"
        row-hover-color="#eee"
        row-click-color="#edf7ff"
      ></v-table>
    </div>
    <!-- <van-pagination
      width="this.screenWidth"
      class="pagination"
      force-ellipses
      v-model="queryParamsRead.pageNum"
      :total-items="queryParamsRead.total"
      @change="pgn_change_read"
      :items-per-page="queryParamsRead.pageSize"
    /> -->
  </div>
</template>
<script>
import {
  DropdownMenu,
  DropdownItem,
  Button,
  Cell,
  Field,
  Col,
  Row,
  Pagination,
  Sticky,
  Toast,
  Dialog,
  Divider,
  Calendar,
} from "vant";
Vue.use(Divider);
Vue.use(Calendar);
Vue.use(Pagination);
Vue.use(Field);
Vue.use(Dialog);
import { _httpClient } from "@/libs/api";
import F2 from "@antv/f2/lib/index-all";
import Header from "@/components/header.vue";
import { VTable } from "vue-easytable";
import "vue-easytable/libs/themes-base/index.css";
import { storage } from "@/libs/utils";
import {
  removeToken,
  getToken,
  setBaseApiFrefix,
  getBaseApiFrefix,
} from "@/libs/auth";
export default {
  components: {
    Button,
    Header,

    Cell,
    Field,
    Col,
    Row,

    Sticky,
    DropdownMenu,
    DropdownItem,
    Divider,
    VTable,
    Dialog,
  },

  data() {
    return {
      //查询条件
      siteIndex: 0, //工厂
      departIndex: 0, //部门
      taskTypeIndex: 0, //任务类型
      valueStr: null, //开始时间查询条件
      valueEnd: null, //结束时间查询条件

      user: [],
      dpIndex: 0,
      //弹窗高度
      autoHeight: {
        height: "",
      },
      showCalendarStr: false,
      showCalendarEnd: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2030, 11, 31),
      showDialog: false,
      queryParamsRead: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [
        {
          seq: "1",
          department: "质量部",
          dayTask: "30",
          weekTask: "20",
          monthTask: "40",
          techTask: "50",
        },
        {
          seq: "1",
          department: "工艺部",
          dayTask: "30",
          weekTask: "20",
          monthTask: "40",
          techTask: "50",
        },
        {
          seq: "1",
          department: "生产部",
          dayTask: "30",
          weekTask: "20",
          monthTask: "40",
          techTask: "50",
        },
      ],
      pointColumns: [
        //表格列头
        {
          field: "seqNum",
          title: "序号",
          width: 50,
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          formatter: function (value, index) {
            return index + 1;
          },
          titleCellClassName: "title-cell-class-name-test",
        },
        {
          field: "requestCode",
          title: "报修单号",
          width: 180,
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          titleCellClassName: "title-cell-class-name-test",
        },
        {
          field: "equipName",
          title: "设备编号",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          titleCellClassName: "title-cell-class-name-test",
        },
        {
          field: "requestTime",
          title: "报修时间",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          titleCellClassName: "title-cell-class-name-test",
        },
        {
          field: "remarkrq",
          title: "故障描述",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          titleCellClassName: "title-cell-class-name-test",
        },
        {
          field: "waitingtime",
          title: "等待时间(分钟)",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "totalmaintenancetime",
          title: "维修时间(分钟)",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "faulttype",
          title: "故障类型",
          width: 100,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "remark",
          title: "维修说明",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "concurrentrepairtime",
          title: "并修时长(分钟)",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "sureconcurrentrepairtime",
          title: "确认并修时长(分钟)",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "disputesureconcurrentrepairtime",
          title: "并修更正(分钟)",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "disputeperson",
          title: "并修更正人员",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "disputetime",
          title: "并修更正时间",
          width: 180,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "rushrepairtime",
          title: "确认抢修时长(分钟)",
          width: 160,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "rushdisputesureconcurrentrepairtime",
          title: "抢修更正(分钟)",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "rushdisputeperson",
          title: "抢修更正人员",
          width: 120,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
        {
          field: "rushdisputetime",
          title: "抢修更正时间",
          width: 180,
          titleAlign: "center",
          columnAlign: "center",
          titleCellClassName: "title-cell-class-name-test",
          isResize: true,
        },
      ],

      columns: [],
      sites: [], //工厂
      departments: [], //部门
      taskTypes: [
        { value: 0, text: "点检" },
        { value: 1, text: "维修" },
      ], //任务类型
      data1: [], //饼图数据
      data: [],
    };
  },
  created: function () {
    let oldHight = api.winWidth;
    this.screenWidth = oldHight;
    //获取当前系统登录用户
    this.user = JSON.parse(storage.get("user"));
    //初始化设置弹窗高度
    this.autoHeight.height = "100px";
    //表格列头初始化
    this.columns = this.pointColumns;

    //初始化查询条件
    this.initQuertSiteList();
  },
  mounted: function () {
    //数据查询
    // this.queryPointCheckData()
  },

  methods: {
    //时间确认查询
    timeConfirm() {
      //重新查询数据
      this.queryPointCheckData();
    },
    pgn_change_read() {
      this.queryPointCheckData();
    },
    //查询点检任务数据
    queryPointCheckData() {
      this.quertPointCheckList();
      this.quertPointCheckTableList();
    },
    //下拉框工厂数据切换
    siteChange(value) {
      this.siteIndex = value;
      this.initQuertDepartList(value);
      //重新查询数据
      this.queryPointCheckData();
    },
    //部门数据切换
    departChange(value) {
      this.departIndex = value;
      //重新查询数据
      this.queryPointCheckData();
    },

    //初始化查询工厂下拉框
    async initQuertSiteList() {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/app/report/siteList"
        );
        if (res.code === 200) {
          if (res.rows.length > 0) {
            _this.sites = [];
            res.rows.forEach(function (item, index) {
              let site = { value: item.siteKey, text: item.siteName };
              _this.sites.push(site);
            });
            _this.siteIndex = _this.sites[0].value;
            _this.initQuertDepartList(_this.siteIndex);
            _this.queryPointCheckData()
          }
        } else {
          //alert(res.msg);
        }
      } catch (e) {
        //alert(JSON.stringify(e));
      }
    },

    //初始化查询部门下拉框
    async initQuertDepartList(val) {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/system/dept/applist",
          {
            body: { parentId: val },
          }
        );
        if (res.code === 200) {
          if (res.data.length > 0) {
            _this.departments = [];
            let depart = { value: 0, text: "所有部门" };
            _this.departments.push(depart);
            for (let i = 0; i < res.data.length; i++) {
              let newDepart = {
                value: res.data[i].deptId,
                text: res.data[i].deptName,
              };
              _this.departments.push(newDepart);
            }
            _this.departIndex = _this.departments[0].value;
          }
        } else {
          //alert(res.msg);
        }
      } catch (e) {
       // alert(JSON.stringify(e));
      }
    },

    //查询图表数据
    async quertPointCheckList() {
      let _this = this;
      //部门
      let deptId = this.departIndex != 0 ? this.departIndex : null;

      //工厂
      let site;
      if (_this.sites.length != 0) {
        site = _this.siteIndex;
      }
      let url = "/pc/report/repairCollect/chartList?siteKey=" + site;
      if (deptId != null) {
        url += "&deptId=" + deptId;
      }
      if (_this.valueStr != null) {
        url += "&startTime=" + _this.valueStr;
      }
      if (_this.endTime != null) {
        url += "&endTime=" + _this.valueEnd;
      }
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + url);
        if (res.code === 200) {
          _this.data = res.list;
          if (res.list != null && res.list.length > 0) {
            _this.data = [];
            for (let i = 0; i < res.list.length; i++) {
              let data1 = {
                deptName:
                  res.list[i].deptName != null
                    ? res.list[i].deptName
                    : "无部门",
                taskType: "报修次数",
                taskNum: res.list[i].requestNum,
              };
              _this.data.push(data1);
              let data2 = {
                deptName:
                  res.list[i].deptName != null
                    ? res.list[i].deptName
                    : "无部门",
                taskType: "响应次数",
                taskNum: res.list[i].responseNum,
              };
              _this.data.push(data2);
              let data3 = {
                deptName:
                  res.list[i].deptName != null
                    ? res.list[i].deptName
                    : "无部门",
                taskType: "维修完成次数",
                taskNum: res.list[i].repairedNum,
              };
              _this.data.push(data3);
              let data4 = {
                deptName:
                  res.list[i].deptName != null
                    ? res.list[i].deptName
                    : "无部门",
                taskType: "未完成次数",
                taskNum: res.list[i].noRepairedNum,
              };
              _this.data.push(data4);
            }
          }
          //调用方法绘制柱形图
          _this.drawChart();
        } else {
          //alert(res.msg);
        }
      } catch (e) {
        //alert(JSON.stringify(e));
      }
    },

    //查询表格数据
    async quertPointCheckTableList() {
      let _this = this;
      //部门
      let deptId = this.departIndex != 0 ? this.departIndex : null;

      //工厂
      let site;
      if (_this.sites.length != 0) {
        site = _this.siteIndex;
      }
      let url =
        "/pc/report/repairCollect/tableListsj?siteKey=" +
        site +
        "&pageNum=" +
        this.queryParamsRead.pageNum +
        "&pageSize=" +
        this.queryParamsRead.pageSize;

      if (deptId != null) {
        url += "&deptId=" + deptId;
      }
      if (_this.valueStr != null) {
        url += "&startTime=" + _this.valueStr;
      }
      if (_this.endTime != null) {
        url += "&endTime=" + _this.valueEnd;
      }

      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
            "/app/repair/requestInfo/checkedListzhengyi99",
          {
            body: {
              site: site,
              startdatetime:_this.valueStr,
              enddatetime:_this.valueEnd
            },
          }
        );
        if (res.code === 200) {
          //alert(JSON.stringify(res));
          _this.tableData = res.rows;
          //_this.queryParamsRead.total = res.total;
        } else {
          //alert(res.msg);
        }
      } catch (e) {
        //alert(JSON.stringify(e));
      }
    },

    //日期格式化
    formatDate(date) {
      let year = date.getFullYear();
      let mouth = date.getMonth() + 1;
      if (mouth < 10) {
        mouth = "0" + mouth;
      }
      let day = date.getDate();
      if (day < 10) {
        day = "0" + day;
      }
      return year + "-" + mouth + "-" + day;
    },

    //时间清空
    clearTime() {
      this.valueStr = "";
      this.valueEnd = "";
      //重新查询数据
      this.queryPointCheckData();
    },

    //开始时间取消
    startConcel() {
      // this.valueStr = ''
      this.autoHeight.height = "100px";
    },
    //结束时间取消
    endConcel() {
      // this.valueEnd = ''
      this.autoHeight.height = "100px";
    },

    //打开开始时间选择
    openStartTime() {
      this.showCalendarStr = true;
      this.autoHeight.height = "400px";
    },

    //打开结束时间选择
    openEndTime() {
      this.showCalendarEnd = true;
      this.autoHeight.height = "400px";
    },

    //开始时间确定
    onConfirmStr(date) {
      this.valueStr = this.formatDate(date);
      this.showCalendarStr = false;
      this.autoHeight.height = "100px";
    },
    //结束时间确认
    onConfirmEnd(date) {
      this.valueEnd = this.formatDate(date);
      this.showCalendarEnd = false;
      this.autoHeight.height = "100px";
    },
    //绘制柱状图
    drawChart() {
      var Shape = F2.Shape;
      var Util = F2.Util;
      Shape.registerShape("interval", "text", {
        draw: function draw(cfg, container) {
          var points = this.parsePoints(cfg.points);
          var style = Util.mix(
            {
              fill: cfg.color,
              z: true, // 需要闭合
            },
            cfg.style
          );
          var intervalShape = container.addShape("rect", {
            attrs: Util.mix(
              {
                x: points[1].x,
                y: points[1].y,
                width: points[2].x - points[1].x,
                height: points[0].y - points[1].y,
              },
              style
            ),
          });

          var origin = cfg.origin._origin; // 获取对应的原始数据记录
          var textShape = container.addShape("text", {
            zIndex: 1,
            attrs: {
              x: (points[1].x + points[2].x) / 2,
              y: points[1].y - 5, // 往上偏移 5 像素
              text: origin["taskNum"],
              fill: "#808080",
              textAlign: "center",
              textBaseline: "bottom",
              fontSize: 12, // 字体大小
            },
          });
          container.sort();
          return [intervalShape, textShape];
        },
      });

      var chart = new F2.Chart({
        id: "mountNode",
        pixelRatio: window.devicePixelRatio,
      });
      chart.source(this.data);
      chart.legend(true);
      chart.legend({
        align: "center",
        itemWidth: null, // 图例项按照实际宽度渲染
      });

      chart.tooltip({
        showItemMarker: false,
        onShow: function onShow(ev) {
          var item = ev.items;
          // alert(JSON.stringify(item))
        },
      });

      chart
        .interval()
        .position("deptName*taskNum")
        // .color('taskType')
        .color("taskType", function (taskType) {
          if (taskType == "报修次数") {
            return "#F0A91D";
          } else if (taskType == "响应次数") {
            return "#3BA4F5";
          } else if (taskType == "维修完成次数") {
            return "#1BCAB9";
          } else if (taskType == "未完成次数") {
            return "#B968E9";
          } else {
            return "#7f8da9";
          }
        })
        .shape("text")
        .adjust({
          type: "dodge",
          marginRatio: 0.2,
        })
        .style({
          radius: [0, 0, 0, 0],
        });

      chart.render();
    },
  },
};
</script>
<style>
body {
  background-color: White;
}
.selectdTextScroll {
  display: inline-block;
  /* position: fixed; */
  top: 9rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  height: 300px;
  z-index: 1;
}
.title-cell-class-name-test {
  background-color: #f8f8f8;
  color: #000000;
}
</style>
